﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NewBusiness;
using NewBusiness.Domain;
using NewBusiness.Domain.Queries;
using NewBusiness.Domain.Uow;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Bson;

namespace NewBusiness.Domain
{
    public interface IUrlContext
    {
        IUrlQueries UrlQueries { get; }
        WriteConcernResult UpsetUrl(string urlId, IEnumerable<BsonElement> bElements);
        MongoCursor<RawBsonDocument> GetUrlsByTags(params string[] tags);
    }

    public class UrlContext : DomainContext, IUrlContext
    {
        private MongoCollection<RawBsonDocument> _urlCollection = null;
        public MongoCollection<RawBsonDocument> UrlCollection
        {
            get
            {
                if (_urlCollection == null)
                {
                    if (!mongoDB.CollectionExists("url"))
                    {
                        mongoDB.CreateCollection("url");
                    }
                    _urlCollection = mongoDB.GetCollection <RawBsonDocument>("url");
                }
                return _urlCollection;
            }
        }
        public IUrlQueries UrlQueries { get; private set; }
        public UrlContext(IUow uow, ISession session, IUrlQueries urlQueries, MongoDB.Driver.MongoDatabase mdb)
            : base(uow, session, mdb)
        {
            this.UrlQueries = urlQueries;
        }
        /// <summary>
        /// Добавляет/изменяет поля или создает новое
        /// </summary>
        public WriteConcernResult UpsetUrl(string urlId, IEnumerable<BsonElement> bElements)
        {
            //var urls = urlId.Split(new[] { "://" }, StringSplitOptions.RemoveEmptyEntries);
            //urlId = urls.Length == 2 ? urls[1] : urls[0];
            //var urlProtocol = urls.Length == 2 ? urls[0] : "";
            var query = Query.EQ("_id", urlId);
            var update = new UpdateBuilder();//.SetOnInsert("_id", urlId);//.Inc("position",1.0);
            foreach (var el in bElements)
            {
                switch (el.Name)
                {
                    case "tags":
                        update = update.AddToSetEach(el.Name, el.Value.AsBsonArray);
                        break;
                    default:
                        update = el.Name == "_id" ? update : update.Set(el.Name, el.Value);
                        break;
                }
            }

            update = update.Set("LastUpdate", new BsonDateTime(DateTime.Now));
            return UrlCollection.Update(query, update, UpdateFlags.Upsert);
        }

        public MongoCursor<RawBsonDocument> GetUrlsByTags(params string[] tags)
        {
            //IMongoQuery query = null;
            var queryes = new IMongoQuery[tags.Length];
            for (int i = 0; i < tags.Length; i++)
            {
                queryes[i] = Query.EQ("tags", tags[i]);
            }
            return UrlCollection.Find(Query.And(queryes));
        }
    }
}
